package com.ruoyi.system.excelImport.pangxie.utils;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.V2.inter.mapper.SalePartnerMapper;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.system.model.domain.SalePartner;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @other pzz
 * @data 2024/8/3
 * @apiNote
 */
@Service
@Slf4j
public class PANGXIEExcelUtils<T> {

    @Autowired
    private SysDictDataMapper sysDictDataMapper;
    @Resource
    private SalePartnerMapper salePartnerMapper;


    static String TOKEN = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJtZXJjaGFudCIsImxvZ2luSWQiOiI0OTY3ODYiLCJyblN0ciI6IkxzdWdibXlWSjhXdUVDdG1kT2xhQld2SDJ5Qlk2Yk5tIiwidXNlck5hbWUiOiIxNzM0NDEyNDk5OSIsIm1lcmNoYW50SWQiOiIxMDAifQ.0S_q70U3MxPT5rlZKajWVPmdmwLh_BHiKG0mPJ8dTdc";
    static String USER_ID = "";

    public JSONObject impostPX(List<T> list, String gameName, SalePartner salePartner) {
        getDictDataToken();
        ExcelUtil<T> util = ExcelUtil.createExcelUtil(gameName);
        String fileName = util.exportExcel(list, "pxExcel", 1);
        String filePath = RuoYiConfig.getDownloadPath() + fileName;
        String importUrl = "https://www.pxb7.com/api/merchant/web/product/batchImportProduct?gameId=__gameId__&sellerId=__sellerId__&contentType=formData";
        importUrl = importUrl.replace("__gameId__", getGameId(gameName)).replace("__sellerId__", salePartner.getThreeOther());

        String body = HttpRequest.post(importUrl)
                .form("file", new File(filePath))
                .header("px-authorization-merchant", salePartner.getSaleKey())
                .header("px-authorization-user", salePartner.getSaleKey())
                .header("client_type", "0")
                .execute().body();

        if (body.contains("登录失败，无法访问系统资源") || body.contains("系统内部错误")) {
            List<SalePartner> salePartnerList = salePartnerMapper.selectSalePartnerListSaleCode("PANGXIE");

            Map<String, List<SalePartner>> collect = salePartnerList.stream().collect(Collectors.groupingBy(s -> s.getOther()));

            for (String phone : collect.keySet()) {
                if (phone.equals(salePartner.getOther())) {
                    List<SalePartner> partners = collect.get(phone);
                    String body1 = HttpRequest.get("http://47.98.139.135:7777/sjpxzh?uname=" + partners.get(0).getOther() + "&pwd=" + partners.get(0).getTwoOther()).execute().body();
                    String token = JSONObject.parseObject(body1).getString("token");
                    if (!token.contains("登录失败！")) {
                        for (SalePartner partner : partners) {
                            partner.setSaleKey(token);
                            salePartnerMapper.updateSalePartner(partner);
                        }
                    }
                }
            }
        }

        JSONObject response = JSONObject.parseObject(body);
        FileUtils.deleteFile(filePath); // 删除错误目录
        log.info(" body   " + body);
        // 删除excel

        return response;
    }

    public static void main(String[] args) {

        String gameName = "使命召唤手游";
        SalePartner partner = new SalePartner();
        partner.setSaleKey("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJtZXJjaGFudCIsImxvZ2luSWQiOiI0OTY3ODYiLCJyblN0ciI6ImFQbVc4UkNQNnJLZERlWFJ5aVFlNU9aa0JMU0R2ckRuIiwidXNlck5hbWUiOiIxNzM0NDEyNDk5OSIsIm1lcmNoYW50SWQiOiIxMDAifQ.2SzNrzTZW11cuMp4vpvByOlyh3ZRF8uWlRyTFiAuTR4");

        List<Long> importIdsCollect = Arrays.asList(54330l);
        List<JSONObject> listPX = getListPX(gameName, partner, importIdsCollect);
        System.out.println(JSONObject.toJSONString(listPX));
    }

    /**
     * 获取所有待审核的帐号
     *
     * @param gameName
     * @return
     */
    public static List<JSONObject> getListPX(String gameName, SalePartner salePartner, List<Long> importIdsCollect) {
        List<JSONObject> resultList = new ArrayList<>();
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String importUrl = "https://www.pxb7.com/api/product/web/merchant/product/query";
        JSONObject data = JSONObject.parseObject("{\"gameId\":\"10036\",\"pageIndex\":1,\"pageSize\":10}");
        data.put("gameId", getGameId(gameName));  // 获取游戏id

        for (Long goodsId : importIdsCollect) {
            for (int index = 1; index < 4; index++) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                data.put("merchantProductId", String.valueOf(goodsId)); // 商家编码
                data.put("status", index);
                String body = HttpRequest.post(importUrl)
                        .body(data.toJSONString())
                        .header("px-authorization-merchant", salePartner.getSaleKey())
                        .header("px-authorization-user", salePartner.getSaleKey())
                        .header("client_type", "0")
                        .execute().body();
                JSONObject dataJson = JSONObject.parseObject(body);
                if (dataJson.getBoolean("success") && dataJson.getJSONArray("data").size() > 0) {
                    List<JSONObject> result = JSONObject.parseArray(dataJson.getString("data"), JSONObject.class);
                    resultList.addAll(result);
                    break;
                }
            }
        }
        return resultList;
    }


    // 获取螃蟹用户id  还有 token
    public Map<String, String> getDictDataToken() {
        Map<String, String> resultMap = new HashMap<>();
        List<SysDictData> sysDictDataList = sysDictDataMapper.selectDictDataByType("pangxie_excel_config");
        for (SysDictData dictData : sysDictDataList) {
            if ("token".equals(dictData.getDictLabel())) {
                TOKEN = dictData.getRemark();
            } else if ("userId".equals(dictData.getDictLabel())) {
                USER_ID = dictData.getDictValue();
            }
        }
        return resultMap;
    }

    // 螃蟹游戏id
    private static String getGameId(String gameName) {
        String gameId = "";
        switch (gameName) {
            case "英雄联盟":
                gameId = "10012";
                break;
            case "王者荣耀":
                gameId = "10013";
                break;
            case "永劫无间":
                gameId = "10023";
                break;
            case "英雄联盟(手游)":
                gameId = "10036";
                break;
            case "枪战王者":
                gameId = "10033";
                break;
            case "无畏契约":
                gameId = "10148";
                break;
            case "原神":
                gameId = "10026";
                break;
            case "永劫无间手游":
                gameId = "10409";
                break;
            case "暗区突围":
                gameId = "10110";
                break;
            case "三角洲行动":
                gameId = "10371";
                break;
            case "使命召唤手游":
                gameId = "10052";
                break;
            default:
                throw new GlobalException("游戏类型错误");
        }
        return gameId;
    }

}
